﻿//Description:废品单集成
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2018-3-15
//Rewriter:
//Rewrite Date:
using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using System.Data.OracleClient;
using System.Xml;

namespace MESContainerStepScrap
{
   public  class SendStepScrap
    {
       private const string m_RecordType = "StepScrap";
       public void RunStepScrapSync()
       {
           DataTable mydt = GetContainerStepScrap();
           if (mydt == null || mydt.Rows.Count <= 0)
           {
             //  LogHelp.WriteLog("没有可处理的废品单记录");
           }
           Dictionary<string, string> strList;
           StepScrapToERP.PS_SAPServicesHttpService sap = new StepScrapToERP.PS_SAPServicesHttpService();
           foreach (DataRow dr in mydt.Rows)
           {
             //  LogHelp.WriteLog("处理废品单记录开始" + dr["CONTAINERID"].ToString());
               strList = new Dictionary<string, string>();

               strList.Add("QMNUM", dr["QMNUM"].ToString());//通知单编号
               if (dr["MATNR"].ToString().Contains("子工艺")) {
                   int n=dr["MATNR"].ToString().IndexOf ("子工艺");
                   strList.Add("MATNR", dr["MATNR"].ToString().Substring (0,n));//物料号
               } else {

                   strList.Add("MATNR", dr["MATNR"].ToString());//物料号
               }

               strList.Add("FERTAUFNR", dr["FERTAUFNR"].ToString());//生产订单号
               strList.Add("FERTVORNR", dr["FERTVORNR"].ToString());//MES工序
               strList.Add("ZMESGXTXT", dr["ZMESGXTXT"].ToString());//MES工序描述
               strList.Add("UVORN", dr["UVORN"].ToString());//子工序
               strList.Add("ZLTXA1", dr["ZLTXA1"].ToString());//子工序描述
               strList.Add("ZZFPLX", dr["ZZFPLX"].ToString());//废品类型
               strList.Add("ZBFLJLX", dr["ZBFLJLX"].ToString()); //报废零件类型	
               strList.Add("ZZFPPLY", dr["ZZFPPLY"].ToString());//生产单位Z2
               strList.Add("ZFPDBH", dr["ZFPDBH"].ToString());// 废品单编号  	
               strList.Add("ZJX", dr["ZJX"].ToString());//	型别
               strList.Add("ZPCH", dr["ZPCH"].ToString());//机加批次
               strList.Add("ZLPH", dr["ZLPH"].ToString());//炉批号
               strList.Add("ZZRDW", dr["ZZRDW"].ToString());//责任单位
               strList.Add("ZZRZ", dr["ZZRZ"].ToString());//	责任者
               strList.Add("ZJYY", dr["ZJYY"].ToString());//检验员
               strList.Add("ZJYSZR", dr["ZJYSZR"].ToString());//检验室主任
               strList.Add("ZGD", dr["ZGD"].ToString());//工段
               strList.Add("ZFPSL", dr["ZFPSL"].ToString()); //	废品数量
               strList.Add("ZFPZL", dr["ZFPZL"].ToString());//废品重量
               strList.Add("ZDW", dr["ZDW"].ToString());//单位     
               strList.Add("ZYWLH", dr["ZYWLH"].ToString());//原料物料号
               strList.Add("ZCLPH1", dr["ZCLPH1"].ToString());//材料牌号
               strList.Add("ZYWLPC1", dr["ZYWLPC1"].ToString());//原料收货批次号
               strList.Add("ZBZ", dr["ZBZ"].ToString());//备注
               strList.Add("QMGRP", dr["QMGRP"].ToString());//编码-代码组
               strList.Add("QMCOD", dr["QMCOD"].ToString());//编码-代码
               strList.Add("ZZTTXT", dr["ZZTTXT"].ToString());//主题长文本（缺陷文本）
               strList.Add("POSNR", dr["POSNR"].ToString());//缺陷-排序号
               strList.Add("FEGRP", dr["FEGRP"].ToString());//缺陷-代码组
               strList.Add("FECOD", dr["FECOD"].ToString());//编码-代码
               strList.Add("FETXT", dr["FETXT"].ToString());//缺陷短文本描述
               strList.Add("ZQXTXT", dr["ZQXTXT"].ToString());//行项目缺陷长文本

               strList.Add("RECORDID", dr["Containerstepscrapinfoid"].ToString());//MES唯一标识
               strList.Add("STATE", dr["isuse"].ToString()=="0"?"I":"D");//处理标识

               strList.Add("ZXMNO1", dr["ZXMNO1"].ToString());//项目1
               strList.Add("ZXMNO2", dr["ZXMNO2"].ToString());//项目2
               strList.Add("ZXMNO3", dr["ZXMNO3"].ToString());//项目3
               strList.Add("ZXMNO4", dr["ZXMNO4"].ToString());//项目4
               strList.Add("ZXMNO5", dr["ZXMNO5"].ToString());//项目5
               strList.Add("ZXMNO6", dr["ZXMNO6"].ToString());//项目6
               strList.Add("ZXMNO7", dr["ZXMNO7"].ToString());//项目7
               strList.Add("ZXMNO8", dr["ZXMNO8"].ToString());//项目8

               strList.Add("ZGAMNG1", dr["ZGAMNG1"].ToString());//数量1
               strList.Add("ZGAMNG2", dr["ZGAMNG2"].ToString());//数量2
               strList.Add("ZGAMNG3", dr["ZGAMNG3"].ToString());//数量3
               strList.Add("ZGAMNG4", dr["ZGAMNG4"].ToString());//数量4
               strList.Add("ZGAMNG5", dr["ZGAMNG5"].ToString());//数量5
               strList.Add("ZGAMNG6", dr["ZGAMNG6"].ToString());//数量6
               strList.Add("ZGAMNG7", dr["ZGAMNG7"].ToString());//数量7
               strList.Add("ZGAMNG8", dr["ZGAMNG8"].ToString());//数量8

               string strXML = CreateXMLForStepScrap(strList);
               LogHelp.WriteLog("推送的消息："+strXML);
               StepScrapToERP.ErpAndAppSyncData mm = new StepScrapToERP.ErpAndAppSyncData();
               mm.ReqMsg = strXML;
               StepScrapToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
               string respMsg = result.RespMsg;
               LogHelp.WriteLog("反馈消息：" + respMsg);//返回消息
               if (result != null)
               {
               //    string strMsg = "";
               //    strMsg = result.RespMsg;
                   string strQMNUM = "";//通知单编号
                   string strZFPDBH = "";//废品单编号
                   if (GetERPRcvXML(respMsg, ref strQMNUM, ref strZFPDBH))
                   {
                       LogHelp.WriteLog("获取的通知单编号：" + strQMNUM + ",获取的废品单编号:" + strZFPDBH);//
                       UpdateStepScrap(dr["ContainerStepScrapInfoID"].ToString(), strQMNUM, strZFPDBH);
                       OracleDAL.InsertSyncRecord(dr["ContainerStepScrapInfoID"].ToString(), m_RecordType, "成功", 0);
                   }
                   else
                   {
                       UpdateStepScrap(dr["ContainerStepScrapInfoID"].ToString(), strQMNUM, strZFPDBH);
                       OracleDAL.InsertSyncRecord(dr["ContainerStepScrapInfoID"].ToString(), m_RecordType, respMsg, 1);
                   }
               }

           }

       }

       /// <summary>
       /// 批次工序废品通知单记录获取,撤销后的也需推送
       /// </summary>
       /// <returns></returns>
       DataTable GetContainerStepScrap() {
           string strSql = @"
                            SELECT T.*  FROM ContainerStepScrapInfo T 
                            "; 
           strSql += @" WHERE  T.ISINTEGRATION = 1 ";
           DataSet myDS = OracleHelper.Query(strSql);
           if (myDS == null)
           {
               return null;
           }
           if (myDS.Tables.Count == 0)
           {
               return null;
           }
           return myDS.Tables[0];
       }

       /// <summary>
       /// 更新报废单信息转接标记
       /// </summary>
       /// <param name="ContainerStepScrapInfoID"></param>
       /// <param name="IsIntegration"></param>
       /// <returns></returns>
       private bool UpdateStepScrap(string ContainerStepScrapInfoID, string strQMNUM, string strZFPDBH)
       {
           string strSql = @"UPDATE ContainerStepScrapInfo SET ISINTEGRATION = 0";
           if (!string.IsNullOrWhiteSpace(strQMNUM))
               strSql += string.Format(" ,qmnum='{0}'", strQMNUM);
           if (!string.IsNullOrWhiteSpace(strZFPDBH))
               strSql += string.Format(" ,ZFPDBH='{0}'", strZFPDBH);
           strSql += " WHERE ContainerStepScrapInfoID = :v_recordid";
           OracleParameter[] insertParam = new OracleParameter[1];

           insertParam[0] = new OracleParameter();
           insertParam[0].ParameterName = ":v_recordid";
           insertParam[0].OracleType = OracleType.VarChar;
           insertParam[0].Direction = ParameterDirection.Input;
           insertParam[0].Value = ContainerStepScrapInfoID;

           int i = OracleHelper.ExecuteSql(strSql, insertParam);
           if (i > 0)
               return true;
           else
               return false;
       }
       /// <summary>
       /// 创建xml字符串
       /// </summary>
       /// <param name="strList"></param>
       /// <returns></returns>
       private string CreateXMLForStepScrap(Dictionary<string, string> strList)
       {

           XmlDocument doc = new XmlDocument();
           doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
           XmlNode ReqNode = doc.CreateElement("ReqMsg");
           XmlNode headerNode = doc.CreateElement("header");
           XmlNode senderNode = doc.CreateElement("sendSysName");
           senderNode.InnerText = "APP_MES";
           XmlNode rcvNode = doc.CreateElement("rcvSysName");
           rcvNode.InnerText = "APP_ERP";
           XmlNode extNode = doc.CreateElement("extConfig");
           extNode.AppendChild(doc.CreateElement("isReTry"));
           extNode.LastChild.InnerText = "false";
           extNode.AppendChild(doc.CreateElement("FunName"));
           extNode.LastChild.InnerText = "ZQMF_MES_FPTZD";
           headerNode.AppendChild(senderNode);
           headerNode.AppendChild(rcvNode);
           headerNode.AppendChild(extNode);
           ReqNode.AppendChild(headerNode);
           XmlNode documentNode = doc.CreateElement("document");
           string strData = "<ALCNRINFO>";
           foreach (KeyValuePair<string, string> _key in strList)
           {
               strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
           }
           strData += "</ALCNRINFO>";
           documentNode.AppendChild(doc.CreateCDataSection(strData));
           ReqNode.AppendChild(documentNode);
           doc.AppendChild(ReqNode);
           return doc.InnerXml;
       }

       /// <summary>
       /// 获取ERP反馈XML
       /// </summary>
       /// <param name="strXML"></param>
       /// <returns></returns>
       private bool GetERPRcvXML(string strXML, ref string strQMNUM, ref string strZFPDBH)
       {
           XmlDocument doc = new XmlDocument();
           doc.LoadXml(strXML);
           string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
           string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

           if (isSuccess == "true" || meaasge == "S")
           {
               string strdocument = doc.SelectSingleNode("RespMsg/document").InnerText;//通知单编号
               XmlDocument tempXml = new XmlDocument();
               tempXml.LoadXml(strdocument);
               strQMNUM = tempXml.SelectSingleNode("ALCNRINFO/QMNUM").InnerText ;
               strZFPDBH = tempXml.SelectSingleNode("ALCNRINFO/ZFPDBH").InnerText;
               return true;
           }
           else
           {
               LogHelp.WriteLog(meaasge);
               return false;
           }
       }

    }
}
